package com.itheima.health.controller;

/**
 * @author ：seanyang
 * @date ：Created in 2019/7/25
 * @description ：
 * @version: 1.0
 */

import com.alibaba.dubbo.config.annotation.Reference;
import com.itheima.health.common.MessageConst;
import com.itheima.health.entity.Result;
import com.itheima.health.service.MemberService;
import com.itheima.health.service.ReportService;
import com.itheima.health.utils.DateUtils;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 统计报表
 */
@RestController
@RequestMapping("/report")
public class ReportController {

 @Reference
 private MemberService memberService;

 @Reference
 private ReportService reportService;


 /**
  * 根据年龄实现的饼状图
  */
 @RequestMapping("/findMemberAgeCount")
 public Result findMemberAgeCount() {
  try {
   List<Map<String, Object>> mapList = memberService.findMemberAgeCount();

   List<String> list = new ArrayList<>();
   for (Map map : mapList) {
    String name = (String) map.get("name");
    list.add(name);
   }

   Map<String, Object> map = new HashMap<>();
   map.put("memberNames", list);
   map.put("memberCount", mapList);
   return new Result(true, MessageConst.ACTION_SUCCESS, map);

  } catch (Exception e) {
   e.printStackTrace();
   return new Result(false, MessageConst.ACTION_FAIL);
  }
 }


 /**
  * 根据前端传入的日期来获取 折线图
  */
 @RequestMapping("/getMemberReportDate")
 public Result getgetMemberReportDate( String id ) {

  System.out.println(id +"----------------------------");


  String[] split = id.split(",");
  ArrayList<String> strings = new ArrayList<>();
  for (String datdString : split) {
   datdString = datdString.replace("GMT", "").replaceAll("\\(.*\\)", "");
   StringBuilder sb = new StringBuilder(datdString);
   sb.insert(26, "+");
   datdString=sb.toString();
   SimpleDateFormat format = new SimpleDateFormat("EEE MMM dd yyyy HH:mm:ss z", Locale.ENGLISH);
   Date dateTrans = null;
   try {
    dateTrans = format.parse(datdString);
    String replace = new SimpleDateFormat("yyyy-MM").format(dateTrans);
    System.out.println(replace);
     strings.add(replace);
   } catch (Exception e) {
    e.printStackTrace();
   }
  }
  String a = strings.get(0);
  System.out.println(a +"++++++++++++++++++++++++++++++++++");
  String b = strings.get(1);
  System.out.println(b  +"++++++++++++++++++++++++++++++++++");

 /* String a = "2019-05";
  String b = "2019-07";*/

  List<String> stringList = null;
 Integer  memberCount = null;
  try {
   stringList = DateUtils.getMonthBetween(a, b);
  } catch (ParseException e) {
   e.printStackTrace();
  }
  List<Integer> str = new ArrayList<>();
  //  2019-05 2019-06 2019-07

  for (String s : stringList){
   // 5  // 5 6 7
   memberCount = memberService.findMemberCountByMonthDate(a,s);
   str.add(memberCount);
  System.out.println(memberCount+"++++++++++++++++++++++++++++++");
  }
  System.out.println(str);
   //返回
   Map<String, Object> returnMap = new HashMap<>();
   returnMap.put("months", stringList);
   returnMap.put("memberCount", str);
   return new Result(true, MessageConst.ACTION_SUCCESS, returnMap);

 // return new Result(true, MessageConst.ACTION_FAIL);
 }
 /**
	 * 获取前12个月，每月会员累计增长总数量
	 * @return
	 */
	@RequestMapping("/getMemberReport")
	public Result getMemberReport(){


		Calendar calendar = Calendar.getInstance();
		// 返回到12个月之前的日期
		calendar.add(Calendar.MONTH,-12);
		try{
			// 获取月份列表
			List<String> monthList = new ArrayList();
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy.MM");
			for (int i= 0 ;i!=12;i++){
				calendar.add(Calendar.MONTH,1);
				monthList.add(sdf.format(calendar.getTime()));
			}
			// 获取月份列表中月份的成员人数
			List<Integer> memberCount = memberService.findMemberCountByMonth(monthList);

			// 封装到返回数据
			Map<String,Object> maps	 = new HashMap<>();
			maps.put("months",monthList);
			maps.put("memberCount",memberCount);
			return new Result(true, MessageConst.ACTION_SUCCESS,maps);
		}catch(Exception e){
			e.printStackTrace();
		}
		return new Result(false,MessageConst.ACTION_FAIL);
	}

	@RequestMapping("/getSetmealReport")
	public Result getSetmealReport(){
		try{
			// 通过service，获取套餐占比数据
			List<Map<String,Object>> setmealCountList = reportService.findSetmealCount();
			// 构建套餐名称列表
			List<String> setmealNames = new ArrayList();
			for (Map<String,Object> currMap:setmealCountList){
				setmealNames.add(currMap.get("name").toString());
			}
			// 把套餐名称列表及套餐占比数据，合并为Map,返回客户端
			Map<String,Object> result = new HashMap<>();
			result.put("setmealNames",setmealNames);
			result.put("setmealCount",setmealCountList);

			return new Result(true,MessageConst.ACTION_SUCCESS,result);
		}catch(Exception e){
		    e.printStackTrace();
		    return new Result(false,MessageConst.ACTION_FAIL);
		}
	}
 @RequestMapping("/getSetmealReportSex")
 public Result getSetmealReportSex(){
  try {
// 通过service 获取套餐占比数据
   List<Map<String, Object>> maplist = reportService.findSetmealCountSex();
   System.out.println(maplist);

   List<String> list = new ArrayList<>();
   for (Map map:maplist) {
    String name = (String)map.get("name");
    if (name.equals("1")){
     name = "男";
    }else{
     name = "女";
    }
    map.put("name",name);
    //listMap.add(map);
    list.add(name);
   }
   // 返回客户端
   HashMap<String, Object> result = new HashMap<>();
   result.put("setmealNames",list);
   result.put("setmealCount",maplist);

   return new Result(true,MessageConst.ACTION_SUCCESS,result);
  } catch (Exception e) {
   e.printStackTrace();
   return new Result(true,MessageConst.ACTION_FAIL);
  }
 }


	@RequestMapping("/getBusinessReportData")
	public Result getBusinessReportData(){
		try{
		    return new Result(true,MessageConst.ACTION_SUCCESS,reportService.findBusinessData());
		}catch(Exception e){
		    e.printStackTrace();
		    return new Result(false,MessageConst.ACTION_FAIL);
		}
	}

	@RequestMapping("/exportBusinessReport")
	public Result exportBusinessReport(HttpServletResponse response){
		try{
		    // 获取运营源数据
			Map<String,Object> reportData = reportService.findBusinessData();
			String strDate = reportData.get("reportDate").toString();
			// 读取excel,获取文件输入流
			InputStream inputStream = this.getClass().getResourceAsStream("/report_template.xlsx");
			// 构建Workbook
			XSSFWorkbook xssfWorkbook = new XSSFWorkbook(inputStream);
			// 获取Sheet
			Sheet sheet = xssfWorkbook.getSheetAt(0);
			// 获取行
			Row row = sheet.getRow(2);
			//  获取列并设置数据，设置报表日期
			row.getCell(5).setCellValue(strDate);
			// 设置会员相关数据

			// 定位到第5行，下标是4
			row = sheet.getRow(4);
			// 设置新增会员及总会员
			row.getCell(5).setCellValue((Long)reportData.get("todayNewMember"));
			row.getCell(7).setCellValue((Long)reportData.get("totalMember"));
			// 设置本周及本月新增会员
			// 定位到第6行，下标是5
			row = sheet.getRow(5);
			row.getCell(5).setCellValue((Long)reportData.get("thisWeekNewMember"));
			row.getCell(7).setCellValue((Long)reportData.get("thisMonthNewMember"));

			// 定位到第8行，下标是7
			// 今日预约及到诊
			row = sheet.getRow(7);
			row.getCell(5).setCellValue((Long)reportData.get("todayOrderNumber"));
			row.getCell(7).setCellValue((Long)reportData.get("todayVisitsNumber"));

			// 本周预约及到诊
			row = sheet.getRow(8);
			row.getCell(5).setCellValue((Long)reportData.get("thisWeekOrderNumber"));
			row.getCell(7).setCellValue((Long)reportData.get("thisWeekVisitsNumber"));

			// 本月预约及到诊
			row = sheet.getRow(9);
			row.getCell(5).setCellValue((Long)reportData.get("thisMonthOrderNumber"));
			row.getCell(7).setCellValue((Long)reportData.get("thisMonthVisitsNumber"));

			// 设置热门套餐列表
			int startRow = 12;
			List<Map<String,Object>> hotSetmealList = (List<Map<String,Object>>)reportData.get("hotSetmeal");
			for (Map<String,Object> currMap:hotSetmealList ){
				String name = currMap.get("name").toString();
				Long setmeal_count = (Long)currMap.get("setmeal_count");
				BigDecimal bigDecimal = (BigDecimal)currMap.get("proportion");
				row = sheet.getRow(startRow);
				row.getCell(4).setCellValue(name);
				row.getCell(5).setCellValue(setmeal_count);
				row.getCell(6).setCellValue(bigDecimal.doubleValue());
				startRow++;
			}
			// 把workbook输出到流
			// 获取输出到客户端的流
			ServletOutputStream outputStream = response.getOutputStream();
			response.setContentType("application/vnd.ms-excel");
			response.setHeader("content-Disposition","attachment;filename="+strDate+"_report.xlsx");
			xssfWorkbook.write(outputStream);
			outputStream.flush();
			outputStream.close();
			xssfWorkbook.close();

			return  null;
		}catch(Exception e){
		    e.printStackTrace();
		    return new Result(false,MessageConst.ACTION_FAIL);
		}
	}
}
